/*
 * Copyright (c) 2012 Universidad Antonio de Nebrija.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Apache License v2.0
 * which accompanies this distribution, and is available at
 * http://www.apache.org/licenses/LICENSE-2.0.html
 * 
 * Contributors:
 *    Universidad Antonio de Nebrija - initial API, implementation and documentation
 */
package com.nebrija.riif.parser;

import org.antlr.runtime.tree.Tree;

import com.nebrija.riif.model.AssertOperator;
import com.nebrija.riif.model.AssertValidation;
import com.nebrija.riif.model.Component;
import com.nebrija.riif.model.RIIFElement;
import com.nebrija.riif.model.RIIFProperties;

/**
 * Class to parse the assertion tokens and build the associated model
 * @author asanchep
 *
 */
public class AssertProcessor implements RIIFParserProcessor {

	public static final String SEPARATOR = "'";

	@Override
	public RIIFElement apply(RIIFElement container, Tree t) {
		// At this moment we only support assertions defined inside a component
		if(! (container instanceof Component)){
			return null;
		}
		// The name of the property the assertion refers to
		String id = t.getChild(0).getText();
		//The affected property might be inside a RIIFProperties object SBE'rate
		String name = parseRealContainerName(id);
		String property = parseRealName(id);
		//Separate into target element and property
		String op = t.getChild(1).getText();
		// Build AssertType
		String expression = t.getChild(2).getText();
		//Actually the expression could be more than 1 children => TODO: turn into for loop
		
		// Get the RIIFProperties element where this property is located
		RIIFProperties target = ((Component)container).getPropertiesElement(name);
		if(target==null){
			return null;
		}
		// Create the assertion representation
		AssertValidation valida = new AssertValidation(
					target, property, AssertOperator.convert(op), expression);
		// Add it to the RIIFProperties object
		target.addAssertion(valida);
		return valida;
	}
	
	protected String parseRealContainerName(String id){
		if(id.indexOf(SEPARATOR)==-1){
			return id;
		}
		return id.substring(0,id.indexOf(SEPARATOR));
	}
	
	
	protected String parseRealName(String id){
		if(id.indexOf(SEPARATOR)==-1){
			return RIIFProperties.VALUE_KEY;
		}
		return id.substring(id.indexOf(SEPARATOR)+1);
	}
}
